package com.yuanxuzhen.androidmedia.audio;

import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioTrackManager {
    private static volatile AudioTrackManager instance;
    private AudioTrack mAudioTrack;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    private int buffersize;
    private ExecutorService executorService;
    private DataInputStream inputStream;

    private AudioTrackManager() {
        init();
    }

    public static AudioTrackManager getInstance() {
        if (instance == null) {
            synchronized (AudioTrackManager.class) {
                if (instance == null) {
                    instance = new AudioTrackManager();
                }
            }
        }
        return instance;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void init() {
        executorService = Executors.newCachedThreadPool();
        AudioFormat.Builder builder = new AudioFormat.Builder();
        builder.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
                .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                .setSampleRate(44100);
        AudioFormat audioFormat = builder.build();

        buffersize = AudioTrack.getMinBufferSize(44100,
                AudioFormat.CHANNEL_OUT_STEREO,
                AudioFormat.ENCODING_PCM_16BIT);
        Log.e("yuanAudioTrack", "init buffersize=" + buffersize);
        AudioAttributes audioAttributes = (new AudioAttributes.Builder()).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
        mAudioTrack = new AudioTrack(
                audioAttributes,
                audioFormat,
                buffersize,
                AudioTrack.MODE_STREAM,
                AudioManager.AUDIO_SESSION_ID_GENERATE
        );

    }


    /**
     * 播放线程
     */
    Runnable recordRunnable = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            try {
                //设置线程的优先级
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
                byte[] tempBuffer = new byte[buffersize];
                int readCount = 0;
                while (inputStream.available() > 0) {
                    readCount= inputStream.read(tempBuffer);
                    if (readCount == AudioTrack.ERROR_INVALID_OPERATION || readCount == AudioTrack.ERROR_BAD_VALUE) {
                        continue;
                    }
                    if (readCount != 0 && readCount != -1) {//一边播放一边写入语音数据
                        //判断AudioTrack未初始化，停止播放的时候释放了，状态就为STATE_UNINITIALIZED
                        if(mAudioTrack.getState() == mAudioTrack.STATE_UNINITIALIZED){
                            init();
                        }
                        mAudioTrack.play();
                        mAudioTrack.write(tempBuffer, 0, readCount);
                    }
                }
                stopPlay();//播放完就停止播放
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };


    private void setPath(String path) throws Exception {
        File file = new File(path);
        inputStream = new DataInputStream(new FileInputStream(file));
    }

    public void stopPlay() {
        try {
            if (mAudioTrack != null) {
                if (mAudioTrack.getState() == AudioRecord.STATE_INITIALIZED) {//初始化成功
                    mAudioTrack.stop();//停止播放
                }
                if (mAudioTrack != null) {
                    mAudioTrack.release();//释放audioTrack资源
                }
            }
            if (inputStream != null) {
                inputStream.close();//关闭数据输入流
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startPlay(String path) {
        try {
            setPath(path);
            executorService.execute(recordRunnable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
